package com.itwen.sms;

import com.itwen.utils.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @program: demo
 * @author: Li Wenwen
 * @create: 2019-02-02 19:31
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
       SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken)authentication;
        UserDetails user = myUserDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
        if (user == null){
            try {
                throw new Exception("无法获取用户信息");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
